package com.syuchen.proxy;

import com.syuchen.client.Client;
import com.syuchen.client.http.HttpClient;
import com.syuchen.client.udp.UdpClient;
import com.syuchen.common.Invocation;
import com.syuchen.common.URL;
import com.syuchen.loadbalance.Loadbalance;
import com.syuchen.register.redisRegister.RedisRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;

public class ProxyFactory {

    //使用Map缓存
    private static HashMap<Class, Object> singletonObjects = new HashMap<>();

    public static <T> T getProxy(Class interfaceClass) {
        Object proxyInstance = singletonObjects.get(interfaceClass);

        if (proxyInstance == null) {
            proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(),
                            method.getParameterTypes(), args);

                    // 服务发现：从注册中心查询要调用的服务的地址
                    List<URL> list = RedisRegister.getServiceUrls(interfaceClass.getName());

                    //负载均衡
                    URL url = Loadbalance.random(list);

                    Client client = new HttpClient();
                    if (URL.UDP_PROTO.equals(url.getTransProtocol())) client = new UdpClient();
                    // 服务调用
                    Object result = null;
                    int retryTimes = 5;
                    int index = list.indexOf(url);
                    while (retryTimes > 0) {
                        try {
                            result = client.send(url, invocation);
                            break;
                        } catch (Exception e) {
                            //服务重试
                            if (++index == list.size()) index = 0;
                            url = list.get(index);
                            if (--retryTimes <= 0) System.out.println("报错了");
                        }
                    }
                    return result;
                }
            });
        }

        return (T) proxyInstance;
    }
}
